﻿using System.Collections.Generic;
using System.Threading.Tasks;
using XCI.Sys.Helper;
using XCI.Sys.Model;
using XCI.Sys.Service;

namespace XCI.Windows
{
    public partial class ModuleOwnerTreeList : BaseUserControl
    {
        private ModuleHelper _moduleHelper;

        public ModuleOwnerTreeList()
        {
            InitializeComponent();
            tree.ModelType = typeof(SysModule);
        }

        public TreeListPlus Tree => tree;
        
        private async Task BindCoreAsync(List<SysModule> list)
        {
            if (_moduleHelper==null) _moduleHelper = new ModuleHelper(tree);

            tree.DataSource = list;
            await _moduleHelper.InitAsync(treeImageList);
            tree.ExpandAll();
        }

        /// <summary>
        /// 根据角色主键加载指定角色拥有的模块
        /// </summary>
        /// <param name="roleId">角色主键</param>
        public async Task LoadByRoleIdAsync(string roleId)
        {
            var modulesList = await SysRoleService.Instance.SelectRolePermissionAsync(roleId);
            await BindCoreAsync(modulesList.Modules);
        }

        /// <summary>
        /// 根据用户主键加载指定用户拥有的模块
        /// </summary>
        /// <param name="userId">用户主键</param>
        public async Task LoadByUserIdAsync(string userId)
        {
            var modulesList = await SysAccountService.Instance.SelectUserPermissionAsync(userId);
            await BindCoreAsync(modulesList.Modules);
        }

        private void treeListx1_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {
            e.NodeImageIndex = _moduleHelper.GetModuleImageIndex(e.Node);
        }
    }
}
